<?php


namespace App\Http\Middleware;


use App\Http\Common\JWT;
use App\Models\AdminUser;
use Closure;

class CheckToken
{
    public function handle($request, Closure $next)
    {
        $header = $request->header('authorization');
        if (!$header) {
            return makeResponse([], '登录失效!', 401);
        };
        $token = substr($header, 7);

        $jwtToken = JWT::verifyToken($token);

        if ($jwtToken['jti'] !== env('JWT_CODE')) {
            return makeResponse([], '签名错误', 500);
        } else {
            $user = AdminUser::where(['username' => $jwtToken['name']])->first()->toArray();
            $status = passwordVerify($jwtToken['pass'], $user['password']);
            unset($user['password']);

            if ($status) {
                $request->merge(['user' => $user]);

            } else {
                return makeResponse([], 'Token验证失败~', 500);
            }

        }
        return $next($request);
    }
}